<template>
    <div class="Editor" ref="Editor"></div>
</template>
<script lang="ts" setup>
import { onLoader } from './init'
import { editor, Uri } from "monaco-editor-core";
import { loadTheme, loadGrammars, prepareVirtualFiles } from "monaco-volar";
import { onMounted, onUnmounted, ref } from 'vue'
import { CodeEditor } from './Store'
import type { StoreState } from './Store'
const Editor = ref();
let editorInstance: editor.IStandaloneCodeEditor;
const FileMapping: Record<string, editor.ITextModel> = {}
let ActiveFile: string;
let ActiveFileName: string;
onMounted(() => {
    onLoader().then(() => {
        Promise.all([loadTheme()]).then(([theme]) => {
            prepareVirtualFiles();
            editorInstance = editor.create(Editor.value, {
                theme,
                automaticLayout: true,
                scrollBeyondLastLine: false,
                colorDecorators: false,
                minimap: {
                    enabled: true,
                },
                inlineSuggest: {
                    enabled: false,
                },
            });
            loadGrammars(editorInstance);
            CodeEditor.onChangeFile((State: StoreState, name: string) => {
                var FileKey = `file:///${name}`;
                ActiveFile = FileKey;
                ActiveFileName = name;
                if (FileMapping[FileKey]) {
                    FileMapping[FileKey].dispose()
                };
                var model = editor.getModel(Uri.parse(FileKey));
                if (model) {
                    model.setValue(State.unSaveCode || State.code);
                    // model.lang
                } else {
                    console.log(State.suffix);
                    model = editor.createModel(State.unSaveCode || State.code, State.suffix, Uri.parse(FileKey));
                }
                FileMapping[FileKey] = model;
                editorInstance.setModel(model);
            })
            CodeEditor.init();
            editorInstance.onDidChangeModelContent(() => {
                var _val = FileMapping[ActiveFile].getLinesContent();
                CodeEditor.SendUnSaveFile(ActiveFileName, _val.join('\n'));
            });
        });
    });
});

const SaveEvent = (event: any) => {
    if (event.key == 's' && event.ctrlKey) {
        event.preventDefault();
        CodeEditor.SaveFile(ActiveFileName);
    };
}

document.addEventListener('keydown', SaveEvent, false)


onUnmounted(() => {
    // for (const key in FileMapping) {
    //     const element = FileMapping[key];
    //     element.dispose()
    // };
    // editor.
    editorInstance.dispose();
    document.removeEventListener('keydown', SaveEvent)
    ActiveFileName = '';
    ActiveFile = '';
})



</script>
<style lang="less" scoped>
.Editor {
    position: absolute;
    top: 35px;
    bottom: 0;
    width: 100%;
}
</style>